<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>点餐系统 - 后台管理</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
    <h1>后台管理</h1>

    <!-- 菜品管理 -->
    <h2>菜品管理</h2>
    <form id="add-dish-form" class="mb-3">
        <div class="mb-3">
            <label for="dishName" class="form-label">菜品名称</label>
            <input type="text" id="dishName" class="form-control" required>
        </div>
        <div class="mb-3">
            <label for="dishPrice" class="form-label">价格</label>
            <input type="number" id="dishPrice" class="form-control" required>
        </div>
        <div class="mb-3">
            <label for="dishDescription" class="form-label">描述</label>
            <textarea id="dishDescription" class="form-control"></textarea>
        </div>
        <button type="submit" class="btn btn-primary">添加菜品</button>
    </form>

    <!-- 菜品列表 -->
    <ul class="list-group mb-5" id="dish-list">
        <!-- 菜品将通过 JavaScript 动态加载 -->
    </ul>

    <!-- 订单管理 -->
    <h2>订单管理</h2>
    <ul class="list-group" id="order-list">
        <!-- 订单将通过 JavaScript 动态加载 -->
    </ul>
</div>

<script>
    // 全局变量
    let dishes = []; // 菜品列表
    let orders = []; // 订单列表

    setupWebSocket()
    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', async () => {
        await fetchDishes();
        await fetchOrders();
        renderDishes();
        renderOrders();
    });

    // 获取菜品列表
    async function fetchDishes() {
        const response = await fetch('api/dish/index');
        const data = await response.json();
        dishes = data.data;
    }

    // 获取订单列表
    async function fetchOrders() {
        const response = await fetch('api/order/index');
        const data = await response.json();
        orders = data.data;
    }

    // 渲染菜品列表
    function renderDishes() {
        const dishList = document.getElementById('dish-list');
        dishList.innerHTML = ''; // 清空现有内容

        dishes.forEach(dish => {
            const dishItem = document.createElement('li');
            dishItem.className = 'list-group-item';

            dishItem.innerHTML = `
                    ${dish.name} - ${dish.price} 元
                    <button onclick="deleteDish(${dish.id})" class="btn btn-danger btn-sm float-end">删除</button>
                `;

            dishList.appendChild(dishItem);
        });
    }

    // 添加菜品
    document.getElementById('add-dish-form').addEventListener('submit', async (e) => {
        e.preventDefault();

        const dishData = {
            name: document.getElementById('dishName').value,
            price: parseFloat(document.getElementById('dishPrice').value),
            description: document.getElementById('dishDescription').value
        };

        const response = await fetch('api/dish/store', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(dishData)
        });

        if (response.ok) {
            alert('菜品添加成功');
            await fetchDishes();
            renderDishes();
        } else {
            alert('菜品添加失败');
        }
    });

    // 删除菜品
    async function deleteDish(dishId) {
        const response = await fetch(`api/dish/${dishId}`, { method: 'DELETE' });

        if (response.ok) {
            alert('菜品删除成功');
            await fetchDishes();
            renderDishes();
        } else {
            alert('菜品删除失败');
        }
    }

    // 渲染订单列表
    function renderOrders() {
        const orderList = document.getElementById('order-list');
        orderList.innerHTML = ''; // 清空现有内容
        orders.forEach(order => {
            const orderItem = document.createElement('li');
            orderItem.className = 'list-group-item';

            orderItem.innerHTML = `
                    订单 ID: ${order.id} - 状态: ${order.status}
                    <select onchange="updateOrderStatus(${order.id}, this.value)" class="form-select form-select-sm float-end" style="width: auto;">
                        <option value="pending" ${order.status === 'pending' ? 'selected' : ''}>待处理</option>
                        <option value="processing" ${order.status === 'processing' ? 'selected' : ''}>处理中</option>
                        <option value="completed" ${order.status === 'completed' ? 'selected' : ''}>已完成</option>
                        <option value="cancelled" ${order.status === 'cancelled' ? 'selected' : ''}>已取消</option>
                    </select>
                `;
            orderList.appendChild(orderItem);
        });
    }

    // 更新订单状态
    async function updateOrderStatus(orderId, status) {
        const response = await fetch(`api/order/updateStatus`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ status: status,id: orderId})
        });

        if (response.ok) {
            alert('订单状态更新成功');
            await fetchOrders();
            renderOrders();
        } else {
            alert('订单状态更新失败');
        }
    }

    function setupWebSocket() {
        const ws = new WebSocket('ws://127.0.0.1:2346');
        ws.onmessage = async (event) => {
            alert('您有新的订单');
            await fetchOrders();
            renderOrders();
        };
    }
</script>
</body>
</html>